import time,datetime
import configparser
import site,os,sys
from Global import mo





if __name__ == '__main__':
    mo.start_time = datetime.datetime.now()
    print("程序开始时间 : ",mo.start_time)
    
    
    
    # 加载配置信息
    config = configparser.ConfigParser()
    config.read("config.ini")
    localtion = config['path']['host']
    port = config['path']['port']
    
    
    # 获取用户site-packages的路径
    print(f"当前 Python 解释器的路径 : {sys.executable}")
    packages_path = os.path.join(site.getsitepackages()[0],"Lib","site-packages")
    if (os.path.exists(packages_path)):
        print(f"当前 Python 解释器所在的第三方包路径 : {packages_path}")
    else:
        print(f"当前 Python 解释器的第三方包路径没有找到!")
        exit()
    
    # 获取所有的 .pth 文件
    pthfiles = []
    for root, dirs, files in os.walk(packages_path):
        for file in files:
            if file.endswith(".pth"):
                pthfiles.append(os.path.join(root, file))

    # 删除原有在Python库目录下的 pth 文件
    for pthfile in pthfiles:
        if os.path.basename(pthfile).startswith("Custom_Python_Pth_File_"):  # 只删除由该程序创建的 pth 文件
            try:
                os.remove(pthfile)
                print(f"成功删除 pth 文件 : {pthfile}")
            except Exception as e:
                print(f"删除 pth 文件 {pthfile} 时出错: {e}")

    # 读取需要进行配置的文件
    pathlines = []
    with open(file=os.path.join(os.path.dirname(__file__),"packagespath.txt"),mode="r",encoding="utf-8") as ff:
        pathlines = ff.readlines()
    pathlines = list(map(lambda x : x.replace("\\","/").replace("//","/"),pathlines))
    
    
    # # 输出所有的.pth 文件
    # print(f"总共扫描到 {pthfiles.__len__()} 个 pth 文件.")
    # for index,pthfile in enumerate(pthfiles,start=1):
    #     print(f"第 {index} 个 pth 文件名 : {pthfile}")

    #     with open(file=pthfile,mode="r",encoding="utf-8") as ff:
    #         lines = ff.readlines()
    for index,path in enumerate(pathlines,start=1):
        createfilepath = os.path.join(packages_path,f"Custom_Python_Pth_File_{index}.pth")
        with open(file=createfilepath,mode="w",encoding="utf-8") as ff:
            ff.write(path)
            print(f"成功创建第 {index} 个 pth 文件 : {createfilepath}")
            ff.close()

    
    mo.end_time = datetime.datetime.now()
    print("程序结束时间 : ",mo.end_time)
    print("程序运行时间 : ",mo.end_time-mo.start_time)
    